import * as mars3d from 'mars3d'
import type { Map } from 'mars3d'
import { MapEngine } from './MapEngine'

type Layer = {
  destroy(): void
  show: boolean
}

export class LayerManager {
  private engine: MapEngine
  private map: Map | null = null
  private layers: Record<string, Layer> = {}
  private baseLayers: Record<string, Layer> = {} // 存储底图图层

  constructor(engine: MapEngine) {
    this.engine = engine
    this.map = engine.getInstance()
  }

  addBaseLayer(options: any) {
    if (!this.map) return null

    const layer = this.map.addLayer(options) as unknown as Layer
    if (layer && options.id) {
      this.layers[options.id] = layer
    }
    return layer
  }

  addWmsLayer(options: any) {
    if (!this.map) return null

    const layer = new mars3d.layer.WmsLayer({
      ...options,
      show: true,
    })
    this.map.addLayer(layer)

    if (options.id) {
      this.layers[options.id] = layer
    }
    return layer
  }

  removeLayer(id: string, destroy = true): boolean {
    const layer = this.layers[id]
    if (layer) {
      if (destroy) {
        layer.destroy()
      }
      delete this.layers[id]
      return true
    }
    return false
  }

  /**
   * 初始化底图
   * @param config 底图配置
   */
  initializeBaseMap(config: any) {
    if (!this.map) {
      console.error('Map instance not available for base map initialization')
      return
    }

    try {
      const { mapType = 'offline', baseMapType, showAnnotation = true, tdtToken } = config

      if (mapType === 'offline') {
        // 离线地图配置
        this._addOfflineBaseMap(baseMapType || 'hebei')
      } else if (mapType === 'online') {
        // 在线天地图配置 - 由MapEngine的basemaps处理，这里不需要额外添加
        console.log(`Online base map configured in MapEngine: ${baseMapType}`)
        return
      }

      console.log(`Base map initialized: ${mapType} - ${baseMapType}`)
    } catch (error) {
      console.error('Failed to initialize base map:', error)
    }
  }

  /**
   * 添加离线底图
   */
  private _addOfflineBaseMap(type: string) {
    let layerOptions: any

    if (type === 'hebei') {
      layerOptions = {
        type: 'tms',
        name: '河北离线地图',
        url: './tiles/hebei/{z}/{x}/{y}.png',
        minimumLevel: 1,
        maximumLevel: 18,
        rectangle: { west: 113.4, south: 36.1, east: 119.2, north: 42.6 }
      }
    } else {
      // global 或其他类型
      layerOptions = {
        type: 'tms',
        name: '全球离线地图',
        url: './tiles/global/{z}/{x}/{y}.png',
        minimumLevel: 1,
        maximumLevel: 18
      }
    }

    const layer = this.addBaseLayer({
      id: `offline_base_${type}`,
      ...layerOptions,
      metadata: { baseLayer: true, mapType: 'offline', baseMapType: type }
    })

    if (layer) {
      this.baseLayers[`offline_base_${type}`] = layer
    }
  }

  /**
   * 添加在线天地图
   */
  private _addOnlineBaseMap(type: string, showAnnotation: boolean, token?: string) {
    const tdtToken = token || '6c99c7793f41fccc4bd595b03711913e'

    let baseLayerOptions: any
    let annotationLayerOptions: any

    switch (type) {
      case 'img':
        baseLayerOptions = {
          type: 'tdt',
          layer: 'img_d',
          key: [tdtToken]
        }
        annotationLayerOptions = {
          type: 'tdt',
          layer: 'img_z',
          key: [tdtToken]
        }
        break
      case 'vec':
        baseLayerOptions = {
          type: 'tdt',
          layer: 'vec_d',
          key: [tdtToken]
        }
        annotationLayerOptions = {
          type: 'tdt',
          layer: 'vec_z',
          key: [tdtToken]
        }
        break
      case 'ter':
        baseLayerOptions = {
          type: 'tdt',
          layer: 'ter_d',
          key: [tdtToken]
        }
        annotationLayerOptions = {
          type: 'tdt',
          layer: 'ter_z',
          key: [tdtToken]
        }
        break
      default:
        console.warn(`Unsupported online base map type: ${type}`)
        return
    }

    // 添加底图
    const baseLayer = this.addBaseLayer({
      id: `online_base_${type}`,
      name: `天地图${type}底图`,
      ...baseLayerOptions,
      metadata: { baseLayer: true, mapType: 'online', baseMapType: type }
    })

    if (baseLayer) {
      this.baseLayers[`online_base_${type}`] = baseLayer
    }

    // 添加注记层
    if (showAnnotation) {
      const annotationLayer = this.addBaseLayer({
        id: `online_annotation_${type}`,
        name: `天地图${type}注记`,
        ...annotationLayerOptions,
        metadata: { annotation: true, mapType: 'online', baseMapType: type }
      })

      if (annotationLayer) {
        this.baseLayers[`online_annotation_${type}`] = annotationLayer
      }
    }
  }

  /**
   * 切换底图
   * @param options 切换选项
   */
  switchBaseMap(options: any): Layer[] {
    if (!this.map) {
      console.error('Map instance not available for base map switching')
      return []
    }

    // 清除当前底图
    this._clearBaseMaps()

    // 初始化新底图
    this.initializeBaseMap(options)

    // 返回新创建的底图图层
    return Object.values(this.baseLayers)
  }

  /**
   * 清除所有底图
   */
  private _clearBaseMaps() {
    Object.keys(this.baseLayers).forEach(id => {
      const layer = this.baseLayers[id]
      if (layer) {
        layer.destroy()
        delete this.baseLayers[id]
        delete this.layers[id]
      }
    })
  }

  /**
   * 获取所有图层
   */
  getAllLayers(): any[] {
    return Object.keys(this.layers).map(id => ({
      id,
      layer: this.layers[id],
      metadata: (this.layers[id] as any).metadata || {}
    }))
  }

  destroy() {
    // 清理底图
    this._clearBaseMaps()

    // 清理其他图层
    Object.values(this.layers).forEach((layer) => {
      layer.destroy()
    })
    this.layers = {}
  }
}
